﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace UnitOfWork
{
    internal class EFRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private DbSet<TEntity> EFSet { get; set; }
        private DbContext EFContext { get; set; }

        public EFRepository(DbContext efContext)
        {
            EFSet = efContext.Set<TEntity>();
            EFContext = efContext;
        }

        public void Insert(TEntity entity)
        {
            EFSet.Add(entity);
        }

        public void Update(TEntity entity)
        {              
            if (EFContext.Entry<TEntity>(entity).State == System.Data.EntityState.Detached)
            {
                EFSet.Attach(entity);
            }
            else
            {
                EFContext.Entry<TEntity>(entity).CurrentValues.SetValues(entity);
            }
            
            EFContext.Entry<TEntity>(entity).State = System.Data.EntityState.Modified;
        }

        public TEntity GetById(params object[] ids)
        {
            return EFSet.Find(ids);
        }

        public IQueryable<TEntity> Get()
        {
            return EFSet;
        }

        public IQueryable<TEntity> Get(System.Linq.Expressions.Expression<Func<TEntity, bool>> filter = null, 
                                        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
        {
            IQueryable<TEntity> query = EFSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            if (orderBy != null)
            {
                return orderBy(query);
            }
            else
            {
                return query;
            }
        }

        public void DeleteById(params object[] ids)
        {
            Delete(GetById(ids));
        }

        public void Delete(TEntity entity)
        {
            if (EFContext.Entry<TEntity>(entity).State == System.Data.EntityState.Detached)
            {
                EFSet.Attach(entity);
            }

            EFSet.Remove(entity);
        }
    }
}
